﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;


namespace MesDock
{
    class ConfigOperate
    {
        #region ini文件作为配置文件
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
            int nSize, string lpFileName);

        [DllImport("kernel32", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);

        private static string ReadString(string section, string key, string def, string filePath)
        {
            StringBuilder temp = new StringBuilder(1024);

            try
            {
                GetPrivateProfileString(section, key, def, temp, 1024, filePath);
            }
            catch (Exception)
            {
                throw;
            }

            return temp.ToString();
        }
        /// <summary>
        /// 根据section取所有key
        /// </summary>
        /// <param name="section"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string[] ReadIniAllKeys(string section, string filePath)
        {
            UInt32 MAX_BUFFER = 32767;

            string[] items = new string[0];

            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));

            UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath);

            if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
            {
                string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);

                items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Marshal.FreeCoTaskMem(pReturnedString);

            return items;
        }
        /// <summary>
        /// 根据section，key取值
        /// </summary>
        /// <param name="section"></param>
        /// <param name="keys"></param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string ReadIniKeys(string section, string keys, string filePath)
        {
            return ReadString(section, keys, "", filePath);
        }
        /// <summary>
        /// 保存ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filePath"></param>
        public static void WriteIniKeys(string section, string key, string value, string filePath)
        {
            WritePrivateProfileString(section, key, value, filePath);
        }
        #endregion

        #region txt文件作为配置文件
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public Dictionary<string, string> getConfig(string filePath)
        {
            Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
            string sLine = "";
            StreamReader streamReader = null;
            try
            {
                streamReader = new StreamReader(filePath);
                while (sLine != null)
                {
                    sLine = streamReader.ReadLine();
                    if (sLine != null && !sLine.Equals(""))
                    {
                        dic.Add(sLine.Substring(0, sLine.IndexOf("=")), sLine.Substring(sLine.IndexOf("=") + 1));
                    }
                }
            }
            catch (Exception ex)
            {
                new MainForm().PrintLog(ex.ToString());
            }
            finally
            {
                streamReader.Close();
            }
            return dic;
        }
        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="ServerAddress"></param>
        /// <param name="AccessToken"></param>
        /// <param name="EquipmentID"></param>
        public void setConfig(string filePath, string ServerAddress, string AccessToken, string EquipmentID)
        {
            FileStream fs = new FileStream(filePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            try
            {
                sw.WriteLine("ServerAddress=" + ServerAddress);
                sw.WriteLine("AccessToken=" + AccessToken);
                sw.WriteLine("EquipmentID=" + EquipmentID);
            }
            catch (Exception ex)
            {
                new MainForm().PrintLog(ex.ToString());
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }
        #endregion
    }
}
